<template>
  <div class="store-container">
    <a-card :bordered="false" class="main-card">
      <div class="page-header">
        <div class="header-left">
          <h1 class="page-title">门店管理</h1>
          <span class="page-description">管理所有门店信息</span>
        </div>
        <a-button type="primary" @click="showAddModal" class="add-button">
          <template #icon><plus-outlined /></template>
          添加门店
        </a-button>
      </div>

      <a-table
        :columns="columns"
        :data-source="storeList"
        :loading="loading"
        rowKey="storeId"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="custom-table"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 0 ? 'green' : 'red'" class="status-tag">
              {{ record.status === 0 ? '营业中' : '已关闭' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'coverImage'">
            <a-image
              :width="100"
              :src="record.coverImage"
              :fallback="'https://via.placeholder.com/100'"
              class="store-image"
            />
          </template>
          <template v-if="column.key === 'action'">
            <div class="action-buttons">
              <a-tooltip title="编辑">
                <edit-outlined class="action-icon edit-icon" @click="handleEdit(record)" />
              </a-tooltip>
              <a-tooltip title="删除">
                <delete-outlined class="action-icon delete-icon" @click="handleDelete(record)" />
              </a-tooltip>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="addModalVisible"
      title="添加门店"
      @ok="handleAdd"
      @cancel="handleCancel"
      class="custom-modal"
    >
      <a-form
        :model="addForm"
        :rules="rules"
        ref="addFormRef"
        layout="vertical"
      >
        <a-form-item label="门店名称" name="storeName">
          <a-input v-model:value="addForm.storeName" placeholder="请输入门店名称" />
        </a-form-item>
        <a-form-item label="地址" name="address">
          <a-input v-model:value="addForm.address" placeholder="请输入门店地址" />
        </a-form-item>
        <a-form-item label="联系电话" name="phone">
          <a-input v-model:value="addForm.phone" placeholder="请输入联系电话" />
        </a-form-item>
        <a-form-item label="营业时间" name="openingHours">
          <a-input v-model:value="addForm.openingHours" placeholder="请输入营业时间" />
        </a-form-item>
        <a-form-item label="封面图" name="coverImage">
          <a-upload
            v-model:file-list="fileList"
            :before-upload="beforeUpload"
            :maxCount="1"
            list-type="picture-card"
            @change="handleChange"
            :show-upload-list="true"
            :customRequest="customRequest"
            class="custom-upload"
          >
            <div v-if="fileList.length < 1">
              <plus-outlined />
              <div style="margin-top: 8px">上传</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="editModalVisible"
      title="修改门店"
      @ok="handleEditSubmit"
      @cancel="handleEditCancel"
      :ok-button-props="{ loading: false }"
      :cancel-button-props="{ disabled: false }"
      class="custom-modal"
    >
      <a-form
        :model="editForm"
        :rules="rules"
        ref="editFormRef"
        layout="vertical"
      >
        <a-form-item label="门店名称" name="name">
          <a-input v-model:value="editForm.name" placeholder="请输入门店名称" />
        </a-form-item>
        <a-form-item label="地址" name="address">
          <a-input v-model:value="editForm.address" placeholder="请输入门店地址" />
        </a-form-item>
        <a-form-item label="联系电话" name="phone">
          <a-input v-model:value="editForm.phone" placeholder="请输入联系电话" />
        </a-form-item>
        <a-form-item label="营业时间" name="openingHours">
          <a-input v-model:value="editForm.openingHours" placeholder="请输入营业时间" />
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="editForm.sort" :min="0" placeholder="请输入排序号" />
        </a-form-item>
        <a-form-item label="封面图" name="coverImage">
          <a-upload
            v-model:file-list="editFileList"
            :before-upload="beforeUpload"
            :maxCount="1"
            list-type="picture-card"
            @change="handleEditChange"
            :show-upload-list="true"
            :customRequest="customEditRequest"
            class="custom-upload"
          >
            <div v-if="editFileList.length < 1">
              <plus-outlined />
              <div style="margin-top: 8px">上传</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { listAllStores, addStore, modify, delStore } from '@/api/store';
import { message, Modal } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { uploadFile } from '@/api/file';
import type { UploadProps } from 'ant-design-vue';

interface Store {
  storeId: string;
  storeName: string;
  address: string;
  phone: string;
  openingHours: string;
  status: number;
  coverImage: string;
  sort: number;
}

const storeList = ref<Store[]>([]);
const loading = ref(false);
const selectedRowKeys = ref<string[]>([]);
const addModalVisible = ref(false);
const editModalVisible = ref(false);
const addFormRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();

const addForm = reactive({
  storeName: '',
  address: '',
  phone: '',
  openingHours: '',
  coverImage: ''
});

const editForm = reactive({
  storeId: '',
  name: '',
  address: '',
  phone: '',
  openingHours: '',
  coverImage: '',
  sort: 0
});

const rules = {
  storeName: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
  name: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  openingHours: [{ required: true, message: '请输入营业时间', trigger: 'blur' }],
  coverImage: [{ required: true, message: '请上传封面图', trigger: 'blur' }],
};

const columns = [
  {
    title: '门店名称',
    dataIndex: 'storeName',
    key: 'storeName',
  },
  {
    title: '地址',
    dataIndex: 'address',
    key: 'address',
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '营业时间',
    dataIndex: 'openingHours',
    key: 'openingHours',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '封面图',
    dataIndex: 'coverImage',
    key: 'coverImage',
  },
  {
    title: '操作',
    key: 'action',
  },
];

const onSelectChange = (selectedKeys: string[]) => {
  selectedRowKeys.value = selectedKeys;
};

const handleDelete = (record: Store) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除门店"${record.storeName}"吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        const res = await delStore(record.storeId);
        if (res.data.code === 200) {
          message.success('删除成功');
          // 重新获取门店列表
          fetchStoreList();
        } else {
          message.error(res.data.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除门店失败:', error);
        message.error('删除失败，请稍后重试');
      }
    },
  });
};

const showAddModal = () => {
  addModalVisible.value = true;
};

const handleAdd = () => {
  addFormRef.value?.validate().then(() => {
    addStore(addForm).then(res => {
      if (res.data.code === 200) {
        message.success('添加成功');
        addModalVisible.value = false;
        fetchStoreList();
      } else {
        message.error(res.data.msg || '添加失败');
      }
    }).catch(error => {
      console.error('添加门店失败:', error);
      message.error('添加失败，请稍后重试');
    });
  });
};

const handleCancel = () => {
  addModalVisible.value = false;
  addFormRef.value?.resetFields();
};

const fetchStoreList = async () => {
  loading.value = true;
  try {
    const res = await listAllStores();
    if (res.data.code === 200) {
      storeList.value = res.data.data;
    } else {
      message.error(res.data.msg || '获取门店列表失败');
    }
  } catch (error) {
    console.error('获取门店列表失败:', error);
    message.error('获取门店列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 文件上传相关
const fileList = ref<any[]>([]);
const editFileList = ref<any[]>([]);

const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件！');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片必须小于2MB！');
    return false;
  }
  return true;
};

// 自定义上传方法
const customRequest = async ({ file, onSuccess, onError }: any) => {
  try {
    const res = await uploadFile(file);
    if (res.data.code === 200) {
      onSuccess(res.data.data);
      addForm.coverImage = res.data.data.url;
      message.success('图片上传成功');
    } else {
      onError(new Error(res.data.msg || '图片上传失败'));
    }
  } catch (error) {
    console.error('图片上传失败:', error);
    onError(error);
    message.error('图片上传失败，请稍后重试');
  }
};

const handleChange: UploadProps['onChange'] = ({ fileList: newFileList, file }) => {
  fileList.value = newFileList;
  if (file.status === 'removed') {
    addForm.coverImage = '';
  }
};

const handleEdit = (record: Store) => {
  editForm.storeId = record.storeId;
  editForm.name = record.storeName;
  editForm.address = record.address;
  editForm.phone = record.phone;
  editForm.openingHours = record.openingHours;
  editForm.coverImage = record.coverImage;
  editForm.sort = record.sort || 0;
  
  // 设置原有的封面图
  if (record.coverImage) {
    editFileList.value = [{
      uid: '-1',
      name: 'cover.jpg',
      status: 'done',
      url: record.coverImage
    }];
  } else {
    editFileList.value = [];
  }
  
  editModalVisible.value = true;
};

const handleEditSubmit = () => {
  if (!editFormRef.value) {
    message.error('表单引用不存在');
    return;
  }

  editFormRef.value.validate()
    .then(() => {
      console.log('提交的表单数据:', editForm);
      return modify(editForm);
    })
    .then(res => {
      if (res.data.code === 200) {
        message.success('修改成功');
        editModalVisible.value = false;
        fetchStoreList();
      } else {
        message.error(res.data.msg || '修改失败');
      }
    })
    .catch(error => {
      console.error('操作失败:', error);
      if (error.errorFields) {
        message.error('请填写完整的表单信息');
      } else {
        message.error('修改失败，请稍后重试');
      }
    });
};

const handleEditCancel = () => {
  editModalVisible.value = false;
  editFormRef.value?.resetFields();
};

const customEditRequest = async ({ file, onSuccess, onError }: any) => {
  try {
    const res = await uploadFile(file);
    if (res.data.code === 200) {
      onSuccess(res.data.data);
      editForm.coverImage = res.data.data.url;
      message.success('图片上传成功');
    } else {
      onError(new Error(res.data.msg || '图片上传失败'));
    }
  } catch (error) {
    console.error('图片上传失败:', error);
    onError(error);
    message.error('图片上传失败，请稍后重试');
  }
};

const handleEditChange: UploadProps['onChange'] = ({ fileList: newFileList, file }) => {
  editFileList.value = newFileList;
  if (file.status === 'removed') {
    editForm.coverImage = '';
  }
};

onMounted(() => {
  fetchStoreList();
});
</script>

<style scoped>
.store-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.main-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.page-description {
  font-size: 14px;
  color: #666;
}

.add-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

.custom-table {
  margin-top: 16px;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 13px;
}

.store-image {
  border-radius: 4px;
  overflow: hidden;
}

.action-buttons {
  display: flex;
  gap: 16px;
}

.action-icon {
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.edit-icon {
  color: #1890ff;
}

.delete-icon {
  color: #ff4d4f;
}

.action-icon:hover {
  transform: scale(1.1);
}

:deep(.ant-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f7fa;
}

:deep(.ant-modal-content) {
  border-radius: 8px;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
}

:deep(.ant-upload-list-picture-card .ant-upload-list-item) {
  border-radius: 8px;
}

:deep(.ant-upload.ant-upload-select-picture-card) {
  border-radius: 8px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .store-container {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .add-button {
    width: 100%;
    justify-content: center;
  }
}
</style> 